package controllers;

import dao.common.CategoryManager;
import dao.common.ImageManager;
import dao.hibernate.CategoryManagerHB;
import dao.hibernate.ImageManagerHB;
import models.helpers.ImageHelper;
import models.shop.CategoryAlias;
import play.Play;
import play.mvc.Controller;
import play.mvc.With;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@With(Secure.class)
public class CategoryAdmin extends Controller {
    private static CategoryManager categoryManager = new CategoryManagerHB();
    private static ImageManager imageManager = new ImageManagerHB();
    @Check("admin")
    public static void edit(int id){
        models.shop.Category category = categoryManager.getForEdit(id);
        render("/Category/edit.html", category);
    }

    @Check("admin")
    public static void update(models.shop.Category c){

    }

    @Check("admin")
    public static void addAlias(CategoryAlias a){
        categoryManager.addAlias(a);
        edit(a.categoryId);
    }

    @Check("admin")
    public static void deleteAlias(int aliasId, int categoryId){
        categoryManager.deleteAlias(aliasId);
        edit(categoryId);
    }
    
    @Check("admin")
    public static void addImage(int categoryId, File image) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(image);
        models.shop.Image img = ImageHelper.saveImage(bufferedImage, Play.getFile("data").toString(), "categories");
        categoryManager.addImage(categoryId, img);
        edit(categoryId);
    }
    
    @Check("admin")
    public static void deleteImage(int categoryId, int imageId){
        models.shop.Image image = imageManager.getById(imageId);
        ImageHelper.deleteImage(image, Play.getFile("data").toString());
        categoryManager.deleteImage(categoryId, imageId);
        edit(categoryId);
    }
}
